package com.neusoft.elmboot.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.neusoft.elmboot.mapper.BusinessMapper;
import com.neusoft.elmboot.service.ex.DataNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.service.BusinessService;

@Service
public class BusinessServiceImpl implements BusinessService{
	
	@Autowired
	private BusinessMapper businessMapper;

	@Override
	public List<Business> listBusinessByOrderTypeId(Integer orderTypeId) {
		List<Business> list = businessMapper.listBusinessByOrderTypeId(orderTypeId);
		if(list != null && !list.isEmpty()){
			return list;
		}
		else{
			throw new DataNotFoundException("该类不存在，获取商家列表失败");
		}
	}
	
	@Override
	public Business getBusinessById(Integer businessId) {
		Business business = businessMapper.getBusinessById(businessId);
		if(business == null){
			throw new DataNotFoundException("该商家不存在，获取商家信息失败");
		}
		return business;
	}

	@Override
	public List<Business> searchBusinesses(String keyword) {
		// 尝试全匹配
		List<Business> results = businessMapper.searchBusinesses(keyword);

		// 如果有结果，直接返回
		if (!results.isEmpty()) {
			return results;
		}

		// 如果没有结果，逐步去掉关键词的一个字符再试
		return searchWithReducedKeyword(keyword);
	}

	private List<Business> searchWithReducedKeyword(String keyword) {
		// 如果关键词长度小于2，则停止搜索
		if (keyword.length() < 2) {
			return new ArrayList<>(); // 无结果，返回空列表
		}

		// 去掉最后一个字符，重新搜索
		String newKeyword = keyword.substring(0, keyword.length() - 1);
		List<Business> results = businessMapper.searchBusinesses(newKeyword);

		// 如果找到结果，返回
		if (!results.isEmpty()) {
			return results;
		}
		// 继续递归，进一步缩短关键词
		return searchWithReducedKeyword(newKeyword);
	}

}
